/*
 *	Copyright © 2013 Changsha Shishuo Network Technology Co., Ltd. All rights reserved.
 *	长沙市师说网络科技有限公司 版权所有
 *	http://www.shishuo.com
 */


package com.hlingsoft.kkh.action;

import com.aliyun.openservices.ClientException;
import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.OSSException;
import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.aliyun.openservices.oss.model.PutObjectResult;
import com.hlingsoft.kkh.dao.*;

import com.hlingsoft.kkh.entity.*;


import com.hlingsoft.kkh.entity.vo.ImageVo;
import com.hlingsoft.kkh.service.AdminPushService;
import com.hlingsoft.kkh.util.Common;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 评论接口
 *
 * @author Selbylei
 */
@Controller
@RequestMapping("/comment")
public class EventCommentsAction extends BaseAction {


    @Autowired
    private EventCommentsDao eventCommentsDao;


    @Autowired
    private ImageDao imageDao;

    @Autowired
    private LikesDao likesDao;

    @Autowired
    private ShareDao shareDao;

    @Autowired
    private ReportDao reportDao;

    @Autowired
    private EventsDao eventsDao;

    @Autowired
    private AdminPushService adminPushService;



    /**
     * 发布评论
     *
     * @param eventsId
     * @param appUserId
     * @param content
     * @param request
     * @return
     */
    @RequestMapping(value = "/add.json",method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> add(
            @RequestParam(value = "eventsId") long eventsId,
            @RequestParam(value = "content") String content,

            @RequestParam(value = "appUserId") long appUserId,
            @RequestParam(value = "longitude") Double longitude,
            @RequestParam(value = "latitude") Double latitude,
            @RequestParam(value = "tokeTimes",required = false) String tokeTimes,
            @RequestParam("files") MultipartFile[] files,




            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            //获取活动
            Events events = eventsDao.getEventsById(eventsId);

            //获取评论人
            AppUser user = userDao.getUserById(appUserId);

            final AppUser eventsUser=userDao.getUserById(events.getAppUserId());

            //添加EventComment
            EventComments eventComments = new EventComments();
            List<Image> imageList = new ArrayList<Image>();

            eventComments.setEventId(eventsId);
            eventComments.setContent(content);
            String images = "";
            List<ImageVo> imageVoList = new ArrayList<ImageVo>();

            if (tokeTimes!=null){
                JSONArray jsonArray = JSONArray.fromObject(tokeTimes);
                long[] tokeTimeArray = (long[]) JSONArray.toArray(jsonArray, long.class);


                for (int i = 0; i < tokeTimeArray.length; i++) {
                    ImageVo imageVo = new ImageVo();
                    imageVo.setFile(files[i]);

                    Date date = Common.transferLongToDate(tokeTimeArray[i]/1000);   //long类型转成Date类型
                    imageVo.setDate(date);
                    imageVoList.add(imageVo);
                }
            }else {


                for (int i = 0; i < files.length; i++) {
                    ImageVo imageVo = new ImageVo();
                    imageVo.setFile(files[i]);
                    imageVo.setDate(new Date());
                    imageVoList.add(imageVo);
                }
            }




            //设值eventComments中的图片
            for (ImageVo imageVo:imageVoList){
                String fileName = imageVo.getFile().getOriginalFilename();
                SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
                String dateString = simpleFormat.format(new Date());
                putObject(dateString, fileName, imageVo.getFile().getInputStream(),
                        imageVo.getFile().getSize());
                images += "http://kkh.oss-cn-hangzhou.aliyuncs.com/upload/" + dateString + "/" + fileName + ",";

            }

            if (images.length() > 0) {
                images = images.substring(0, images.length() - 1);
            }
            eventComments.setImage(images);

            //图片插入图片表
            eventComments.setLikeCount(0);
            eventComments.setUnlikeCount(0);
            eventComments.setShareCount(0);
            eventComments.setAppUserId(appUserId);
            eventComments.setCreateTime(new Date());
            eventComments.setUpdateTime(new Date());
            eventComments.setAvailable(1);
            eventComments.setType(0);
            eventCommentsDao.addEventComments(eventComments);






            //添加图片
            for (ImageVo imageVo:imageVoList){
                Image image = new Image();

                //图片地址
                String fileName = imageVo.getFile().getOriginalFilename();
                SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
                String dateString = simpleFormat.format(new Date());
                putObject(dateString, fileName, imageVo.getFile().getInputStream(),
                        imageVo.getFile().getSize());
                String path =  "http://kkh.oss-cn-hangzhou.aliyuncs.com/upload/" + dateString + "/" + fileName;
                image.setPath(path);

                image.setAppUserId(appUserId);
                image.setEventCommentsId(eventComments.getId());
                image.setEventsId(eventsId);
                image.setTagId(0);
                image.setCreateTime(new Date());
                image.setUpdateTime(new Date());
                image.setTokeTime(imageVo.getDate());
                image.setAvailable(1);
                imageDao.addImage(image);
            }

            resultMap.put("images", images);  //返回图片
            resultMap.put("result", true);

            //消息推送
            String alert = user.getName()+"在你的社区里发了一张图，快去看看";
            adminPushService.pushToClient(alert, new ArrayList<String>() {
                {
                    add(eventsUser.getUdId());
                }
            }, AdminPushService.JOB, false,true);


        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * andriod创建评论
     * @param eventsId
     * @param content
     * @param appUserId
     * @param longitude
     * @param latitude
     * @param tokeTimes
     * @param file1
     * @param file2
     * @param file3
     * @param file4
     * @param request
     * @return
     */
    @RequestMapping(value = "/addC.json",method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> addC(



            @RequestParam(value = "eventsId") long eventsId,
            @RequestParam(value = "content") String content,

            @RequestParam(value = "appUserId") long appUserId,
            @RequestParam(value = "longitude") Double longitude,
            @RequestParam(value = "latitude") Double latitude,
            @RequestParam(value = "tokeTimes") String tokeTimes,
            @RequestParam(value = "file1",required = false) MultipartFile file1,
            @RequestParam(value = "file2",required = false) MultipartFile file2,
            @RequestParam(value = "file3",required = false) MultipartFile file3,
            @RequestParam(value = "file4",required = false) MultipartFile file4,


            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            //获取活动
            Events events = eventsDao.getEventsById(eventsId);

            //获取评论人
            final AppUser user = userDao.getUserById(appUserId);

            //添加EventComment
            EventComments eventComments = new EventComments();
            List<Image> imageList = new ArrayList<Image>();

            eventComments.setEventId(eventsId);
            eventComments.setContent(content);
            String images = "";

            JSONArray jsonArray = JSONArray.fromObject(tokeTimes);
            long[] tokeTimeArray = (long[]) JSONArray.toArray(jsonArray, long.class);

            List<MultipartFile> filesList = new ArrayList<MultipartFile>();
            if (file1!=null){
                filesList.add(file1);
            }
            if (file2!=null){
                filesList.add(file2);
            }
            if (file3!=null){
                filesList.add(file3);
            }
            if (file4!=null){
                filesList.add(file4);
            }

            List<ImageVo> imageVoList = new ArrayList<ImageVo>();
            for (int i = 0; i < tokeTimeArray.length; i++) {
                ImageVo imageVo = new ImageVo();
                imageVo.setFile(filesList.get(i));

                Date date = Common.transferLongToDate(tokeTimeArray[i]/1000);   //long类型转成Date类型
                imageVo.setDate(date);
                imageVoList.add(imageVo);
            }



            //设值eventComments中的图片
            for (ImageVo imageVo:imageVoList){
                String fileName = imageVo.getFile().getOriginalFilename();
                SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
                String dateString = simpleFormat.format(new Date());
                putObject(dateString, fileName, imageVo.getFile().getInputStream(),
                        imageVo.getFile().getSize());
                images += "http://kkh.oss-cn-hangzhou.aliyuncs.com/upload/" + dateString + "/" + fileName + ",";

            }

            if (images.length() > 0) {
                images = images.substring(0, images.length() - 1);
            }
            eventComments.setImage(images);

            //图片插入图片表
            eventComments.setLikeCount(0);
            eventComments.setUnlikeCount(0);
            eventComments.setShareCount(0);
            eventComments.setAppUserId(appUserId);
            eventComments.setCreateTime(new Date());
            eventComments.setUpdateTime(new Date());
            eventComments.setAvailable(1);
            eventComments.setType(0);
            eventCommentsDao.addEventComments(eventComments);


            //添加图片
            for (ImageVo imageVo:imageVoList){
                Image image = new Image();

                //图片地址
                String fileName = imageVo.getFile().getOriginalFilename();
                SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
                String dateString = simpleFormat.format(new Date());
                putObject(dateString, fileName, imageVo.getFile().getInputStream(),
                        imageVo.getFile().getSize());
                String path =  "http://kkh.oss-cn-hangzhou.aliyuncs.com/upload/" + dateString + "/" + fileName;
                image.setPath(path);

                image.setAppUserId(appUserId);
                image.setEventCommentsId(eventComments.getId());
                image.setEventsId(eventsId);
                image.setTagId(0);
                image.setCreateTime(new Date());
                image.setUpdateTime(new Date());
                image.setTokeTime(imageVo.getDate());
                image.setAvailable(1);
                imageDao.addImage(image);
            }

            resultMap.put("images", images);  //返回图片
            resultMap.put("result", true);

            //消息推送
            String alert = user.getName()+"在你的社区里发了一张图，快去看看";
            adminPushService.pushToClient(alert, new ArrayList<String>() {
                {
                    add(user.getUdId());
                }
            }, AdminPushService.JOB, false,true);

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }






    /**
     * 点赞
     *
     * @param userId
     * @param eventCommentsId
     * @param request
     * @return
     */
    @RequestMapping(value = "/like.json")
    @ResponseBody
    public Map<String, Object> like(
            @RequestParam(value = "userId", defaultValue = "0") long userId,
            @RequestParam(value = "eventCommentsId") long eventCommentsId,

            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {

            //更新eventComments表
            EventComments eventComments = eventCommentsDao.getCommentsListById(eventCommentsId);
            eventComments.setLikeCount(eventComments.getLikeCount() + 1);
            eventComments.setUpdateTime(new Date());
            eventCommentsDao.updateEventComments(eventComments);

            //更新like表
            Likes likes = new Likes();
            likes.setMyId(userId);
            likes.setAppUserId(eventComments.getAppUserId());
            likes.setEventCommentsId(eventCommentsId);
            likes.setEventsId(eventComments.getEventId());
            likes.setCreateTime(new Date());
            likes.setUpdateTime(new Date());
            likesDao.addLikes(likes);

            resultMap.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 举报
     *
     * @param userId
     * @param content
     * @param email
     * @param eventCommentsId
     * @param request
     * @return
     */
    @RequestMapping(value = "/report.json", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> report(
            @RequestParam(value = "userId") long userId,
            @RequestParam(value = "content") String content,
            @RequestParam(value = "email") String email,
            @RequestParam(value = "eventCommentsId") long eventCommentsId,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
//            Report report = new Report();
//            report.setAppUserId(userId);
//            report.setContent(content);
//            report.setEmail(email);
//            report.setEventCommentsId(eventCommentsId);
//
//            reportDao.addReport(report);
            resultMap.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * @param EventCommentsId
     * @param request
     * @return
     */
    @RequestMapping(value = "/unlike.json")
    @ResponseBody
    public Map<String, Object> unlike(
            @RequestParam(value = "EventCommentsId") long EventCommentsId,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {

            EventComments eventComments = eventCommentsDao.getCommentsListById(EventCommentsId);
            eventComments.setUnlikeCount(eventComments.getUnlikeCount() + 1);
            eventComments.setUpdateTime(new Date());
            eventCommentsDao.updateEventComments(eventComments);
            resultMap.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }




    /**
     * 分享
     *
     * @param userId
     * @param imageId
     * @param eventCommentsId
     * @param request
     * @return
     */
    @RequestMapping(value = "/share.json")
    @ResponseBody
    public Map<String, Object> share(
            @RequestParam(value = "userId", defaultValue = "0") long userId,
            @RequestParam(value = "eventsId") long eventsId,
            @RequestParam(value = "imageId") long imageId,
            @RequestParam(value = "eventCommentsId", defaultValue = "0", required = false) long eventCommentsId,
            HttpServletRequest request) {

        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {

            if (eventCommentsId == 0) {
                EventComments eventComments = eventCommentsDao.getFirstEventComments(eventsId);
                eventCommentsId = eventComments.getId();
            }

            //更新eventComments表
            EventComments eventComments = eventCommentsDao.getCommentsListById(eventCommentsId);
            eventComments.setShareCount(eventComments.getShareCount() + 1);
            eventComments.setUpdateTime(new Date());
            eventCommentsDao.updateEventComments(eventComments);

            //更新share表
            Date now = new Date();
            Share share = new Share();
            share.setMyId(userId);
            share.setAppUserId(eventComments.getAppUserId());
            share.setEventCommentsId(eventCommentsId);
            share.setEventsId(eventComments.getEventId());

            Image image = imageDao.getImageById(imageId);
            share.setImage(image.getPath());

            share.setImageId(image.getId());
            share.setCreateTime(now);
            share.setUpdateTime(now);
            shareDao.addShare(share);


            resultMap.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 互动评论
     *
     * @param EventCommentsId
     * @param request
     * @return
     */
    @RequestMapping(value = "/interaction.json")
    @ResponseBody
    public Map<String, Object> interaction(
//
            @RequestParam(value = "appUserId") long appUserId,
            @RequestParam(value = "EventCommentsId") long EventCommentsId,
            @RequestParam(value = "content") String content,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            AppUser user = userDao.getUserById(appUserId);

            EventComments eventComments = eventCommentsDao.getCommentsListById(EventCommentsId);

            final AppUser eventCommentsUser = userDao.getUserById(eventComments.getAppUserId());
            long eventsId = eventComments.getEventId();

            eventComments.setEventId(eventsId);
            eventComments.setContent(content);

            eventComments.setToName(userDao.getUserById(eventComments.getAppUserId()).getName());

            eventComments.setImage("");
            eventComments.setLikeCount(0);
            eventComments.setUnlikeCount(0);
            eventComments.setShareCount(0);
            eventComments.setAppUserId(appUserId);
            eventComments.setCreateTime(new Date());
            eventComments.setUpdateTime(new Date());
            eventComments.setType(0);
            eventCommentsDao.addEventComments(eventComments);

            String alert = user.getName()+"在你创建的社区跟贴了";
            adminPushService.pushToClient(alert, new ArrayList<String>() {
                {
                    add(eventCommentsUser.getUdId());
                }
            }, AdminPushService.JOB, false,true);

            resultMap.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    public void putObject(String date, String filename, InputStream content,
                          Long size) throws FileNotFoundException {

        // 初始化OSSClient


        OSSClient client = new OSSClient("W6PVM427mSEWlvEz",
                "h7NoXlxcjCqyeOWeuT43LungGmGRSd");

        // 获取指定文件的输入流
        // File file = new File(filePath);
        // InputStream content = new FileInputStream(file);

        // 创建上传Object的Metadata
        ObjectMetadata meta = new ObjectMetadata();

        // 必须设置ContentLength
        meta.setContentLength(size);

        // 上传Object.
        PutObjectResult result = client.putObject("kkh", "upload/" + date
                + "/" + filename, content, meta);

        // 打印ETag
        System.out.println(result.getETag());
    }


}
